<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Coach;
use App\Models\CoachConfig;
use App\Models\Comment;
use App\Models\Student;
use App\Models\StudentState;
use App\Models\User;
use App\Models\Evaluate;
use App\Models\Complaint;
use App\Repositories\SchoolRepository;
use App\Repositories\ServiceRepository;
use App\Repositories\StudentCountRepository;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends BaseController
{
    protected $student_count;
    protected $service;
    protected $school;

    public function __construct(
        StudentCountRepository $student_count,
        ServiceRepository $service,
        SchoolRepository $school
    )
    {
        $this->student_count = $student_count;
        $this->service = $service;
        $this->school = $school;
    }


    /**
     * @api {post} /authorizations 用户登陆
     * @apiDescription 用户登陆
     * @apiGroup Auth
     * @apiPermission none
     * @apiSampleRequest /api/authorizations
     * @apiParam {String} [username=] 用户名
     * @apiParam {String} [password]  密码
     * @apiParam {Number} [type=1]  类型  1：学员 2：教练 3：驾校
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": {
     *           "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vZGV2LmpzX2FwaS5jb20vYXBpL2F1dGhvcml6YXRpb25zIiwiaWF0IjoxNDkxOTg3MDQ1LCJleHAiOjE0OTE5OTQyNDUsIm5iZiI6MTQ5MTk4NzA0NSwianRpIjoibkQ4NndDelNHTkV2Qk1pZSIsInN1YiI6MX0.uKYhJzKPC5Y-bJEwgBoJ7xJe-EGpgOLSPpSTFndb8nE",
     *           "expired_at": "2017-04-12 10:50:45",
     *           "refresh_expired_at": "2017-04-26 08:50:45"
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required',
            'type' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->errorResponse($validator->errors()->first()); //数据验证
        }
        $credentials = $request->only('username', 'password');
        $type = $request->get('type');
        if($type==1){//学员
            if(strlen($credentials['username'])==18){//身份证登陆
                $user = User::where('username',$credentials['username'])->where('item_type','App\Models\Student')->first();
                $student = Student::where('idcard',$credentials['username'])->first();

                if(!$student) {

                    return $this->errorResponse('账号不存在');
                }elseif($student->graduation == 2){
                    return $this->errorResponse('该学员已经退学了');
                }elseif($student->graduation == 1){
                    return $this->errorResponse('该学员已经结业，请联系驾校');
                }

                if(!$student->stunum){
                    $student->stunum = date('YmdHis',time()).rand(10,99);
                    $student->save();
                }

                if(!$user){//不存在 写入新账号数据
                    $data = [
                        'username'=>$credentials['username'],
                        'password'=>bcrypt(msubstr($credentials['username'],count($credentials['username'])-7,6)),
                        'name'=>$student->name,
                        'item_id'=>$student->id,
                        'item_type'=>'App\Models\Student',
                        'created_at'=>Carbon::now()->toDateTimeString(),
                        'updated_at'=>Carbon::now()->toDateTimeString()
                    ];
                    $id = User::insertGetId($data);
                    if(!$id){
                        return $this->errorResponse('创建用户失败');
                    }
                }

            }elseif (strlen($credentials['username'])==11){//绑定手机登陆

                $student = Student::where('phone','like',$credentials['username'])->first();

                if(!$student ){//不存在
                    return $this->errorResponse('账号不存在');
                }else{
                    $credentials['username'] = $student->idcard;
                }

            }

        }elseif($type==2){//教练
            if(strlen($credentials['username'])==18){//身份证登陆
                $coach = Coach::where('idcard',$credentials['username'])->first();
                if($coach){//不存在 写入新账号数据

                    $user = User::where('username',$credentials['username'])->where('item_type','App\Models\Coach')->first();
                    if(!$user) {
                        $data = [
                            'username' => $credentials['username'],
                            'password' => bcrypt(msubstr($credentials['username'], count($credentials['username']) - 7, 6)),
                            'name' => $coach->name,
                            'item_id' => $coach->id,
                            'item_type' => 'App\Models\Coach',
                            'created_at' => Carbon::now()->toDateTimeString(),
                            'updated_at' => Carbon::now()->toDateTimeString()
                        ];
                        $id = User::insertGetId($data);
                        if (!$id) {
                            return $this->errorResponse('创建用户失败', 401);
                        }
                    }
                }else{
                    return $this->errorResponse('账号不存在');
                }
            }elseif (strlen($credentials['username'])==11){//绑定手机登陆
                $coach = Coach::where('mobile','like',$credentials['username'])->first();

                if($coach){//不存在 写入新账号数据

                    $user = User::where('username',$coach->idcard)->where('item_type','App\Models\Coach')->first();
                    if(!$user) {
                        $data = [
                            'username' => $coach->idcard,
                            'password' => bcrypt(msubstr($coach->idcard, count($coach->idcard) - 7, 6)),
                            'name' => $coach->name,
                            'item_id' => $coach->id,
                            'item_type' => 'App\Models\Coach',
                            'created_at' => Carbon::now()->toDateTimeString(),
                            'updated_at' => Carbon::now()->toDateTimeString()
                        ];
                        $id = User::insertGetId($data);
                        if (!$id) {
                            return $this->errorResponse('创建用户失败', 401);
                        }
                    }
                    $credentials['username'] = $coach->idcard;
                }else{//不存在
                    return $this->errorResponse('账号不存在');
                }
            }
        }elseif($type == 3){//驾校登录






        }


        // 验证失败返回403
        if (! $token = \Auth::attempt($credentials)) {
            //dd(trans('auth.incorrect'));
            return $this->errorResponse(trans('auth.incorrect'));
        }

        if($type == 2 && !\Auth::user()->item->school->ischeck){
            return $this->successResponse('驾校被限制登录，请联系驾校',[], 201);
        }else if($type == 3 && !\Auth::user()->item->ischeck){
            return $this->successResponse('驾校被限制登录，请联系客服人员：028-962570',[], 201);
        }


        $data = [
            'token' => $token,
            'expired_at' => Carbon::now()->addMinutes(config('jwt.ttl'))->toDateTimeString(),
            'refresh_expired_at' => Carbon::now()->addMinutes(config('jwt.refresh_ttl'))->toDateTimeString(),
        ];
        //学员登录----------
        if($type == 1){
            $service_info = $this->service->getByServiveInfo(\Auth::user()->item->service_id);//服务项目及权限

            if(!$service_info){
                return $this->successResponse('没有设置服务项目，请联系驾校',[], 201);
            }elseif(!$service_info->config){
                return $this->successResponse('没有设置服务项目权限，请联系驾校',[], 201);
            }


            //更新用户登录token到数据库
            $this->updateToken(\Auth::user()->item, $token);


            if(\Auth::user()->item_type == 'App\Models\Student'){
                $user = \Auth::user()->item;
                $data['photo'] = $user->photo;
                $data['name'] = $user->name;
                $data['school_id'] = $user->school->id;
                $data['id'] = $user->id;
                $data['traintype'] = traintypeName($user->traintype);
                $data['school_name'] = $user->school->name;
                $data['mycomment'] = Comment::where('student_id', $user->id)->count();
                $data['mycomplain'] = StudentState::where('student_id', $user->id)->count();
                $data['mywallet'] = $this->student_count->walletTotal($user);
                $data['service_phone'] = '';
                if($user->service_id){
                    $data['service_phone'] = $user->service->service_tel;
                }
            }

        }
        //教练登录----------
        if($type == 2){

            //更新用户登录token到数据库
            $this->updateCoachToken(\Auth::user()->item, $token);

            if(\Auth::user()->item_type == 'App\Models\Coach'){
                $user = \Auth::user()->item;
                $data['school_id'] = $user->school->id;
                $data['photo'] = $user->photo;
                $data['name'] = $user->name;
                $data['id'] = $user->id;
                $data['traintype'] = traintypeName($user->traintype);
                $data['school_name'] = $user->school->name;
                $data['mycomment'] = Comment::where('coach_id', $user->id)->count();
                $data['mycomplain'] = StudentState::where('coach_id', $user->id)->count();
                $data['service_phone'] = '';
                if($user->service_id){
                    $data['service_phone'] = $user->service->service_tel;
                }

                $coach_config = CoachConfig::where('coach_id', $user->id)->where('type', 1)->first();
                $school_coach_config = CoachConfig::where('school_id', $user->school_id)->where('type', 2)->first();
                if($coach_config){
                    $data['permit_config'] = $coach_config ? $coach_config : [];
                }elseif($school_coach_config){
                    $data['permit_config'] = $school_coach_config ? $school_coach_config : [];
                }else{
                    $coach_config['ch_template'] = 1;
                    $coach_config['ch_remove_putime'] =1;
                    $coach_config['ch_open_putime'] = 1;
                    $coach_config['ch_open_putime_day'] = 3;
                    $coach_config['ch_help_putime'] = 1;
                    $coach_config['ch_cancel_putime'] = 1;
                    $coach_config['ch_cancel_putime_hour'] = 2;
                    $coach_config['ch_look_comment'] = 1;
                    $coach_config['ch_look_toushu'] = 1;
                    $coach_config['ch_open_studentlist'] = 1;
                    $coach_config['ch_open_studentinfo'] = 1;
                    $coach_config['ch_leave'] = 1;
                    $data['permit_config'] = $coach_config;
                }

            }

        }
        //驾校登录----------
        if($type == 3){
            $data['name'] = \Auth::user()->item->name;
            $data['school_id'] = \Auth::user()->item->id;
        }


        $result = [
            'message'=>'ok',
            'status_code'=>200,
            'data'=>$data
        ];


        return $this->successResponse('success',$result);
    }

    /**
     * @api {put} /authorizations/current 刷新token(refresh token)
     * @apiDescription 刷新token(refresh token)
     * @apiSampleRequest /api/authorizations/current
     *
     * @apiGroup Auth
     * @apiPermission JWT
     * @apiVersion 1.0.0
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiHeaderExample {json} Header-Example:
     *     {
     *       "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL21vYmlsZS5kZWZhcmEuY29tXC9hdXRoXC90b2tlbiIsImlhdCI6IjE0NDU0MjY0MTAiLCJleHAiOiIxNDQ1NjQyNDIxIiwibmJmIjoiMTQ0NTQyNjQyMSIsImp0aSI6Ijk3OTRjMTljYTk1NTdkNDQyYzBiMzk0ZjI2N2QzMTMxIn0.9UPMTxo3_PudxTWldsf4ag0PHq1rK8yO9e5vqdwRZLY"
     *     }
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": {
     *           "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vZGV2LmpzX2FwaS5jb20vYXBpL2F1dGhvcml6YXRpb25zIiwiaWF0IjoxNDkxOTg3MDQ1LCJleHAiOjE0OTE5OTQyNDUsIm5iZiI6MTQ5MTk4NzA0NSwianRpIjoibkQ4NndDelNHTkV2Qk1pZSIsInN1YiI6MX0.uKYhJzKPC5Y-bJEwgBoJ7xJe-EGpgOLSPpSTFndb8nE",
     *           "expired_at": "2017-04-12 10:50:45",
     *           "refresh_expired_at": "2017-04-26 08:50:45"
     *       }
     *   }
     */
    public function update()
    {
        $token = '';
        try{
            $token = JWTAuth::parseToken()->refresh();//刷新token
        }catch (JWTException $e) {
            return $this->errorResponse( $e->getMessage());
        }

        $user = JWTAuth::setToken($token)->authenticate();

        $this->updateToken($user->item, $token);

        $data = [
            'token' => $token,
            'expired_at' => Carbon::now()->addMinutes(config('jwt.ttl'))->toDateTimeString(),
            'refresh_expired_at' => Carbon::now()->addMinutes(config('jwt.refresh_ttl'))->toDateTimeString(),
        ];

        if($user->item_type != 'App\Models\School'){
            $user = $user->item;
            $data['photo'] = $user->photo;
            $data['name'] = $user->name;
            $data['id'] = $user->id;
            $data['traintype'] = traintypeName($user->traintype);
            $data['school_name'] = $user->school->name;
            $data['mycomment'] = Comment::where('student_id', $user->id)->count();
            $data['mycomplain'] = StudentState::where('student_id', $user->id)->count();
            $data['mywallet'] = $this->student_count->walletTotal($user);
        }

        $result = [
            'message'=>'ok',
            'status_code'=>200,
            'data'=>$data,
        ];

        return $this->successResponse('success',$result);
    }

//
//    public function destroy()
//    {
//        \Auth::logout();
//        return $this->response->noContent();
//    }

}
